//
//  MCAlert.m
//  iMooc
//
//  Created by CoderXSLee on 13/5/3.
//  Copyright © 2013年 李雪松. All rights reserved.
//

#import "MCAlert.h"

@interface MCAlert() <UITextFieldDelegate>

@end

@implementation MCAlert {
    BOOL hasCancelBtn;
    NSMutableArray *argsArray;
    NSString *titleText;
    NSString *messageText;
}

/**
 *  处理通知
 */
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
/**
 *  创建alertView
 *
 *  @param title             提示标题
 *  @param message           提示详情文字长度小于20时并且只有两个按钮时，一左一右，否则上下摆放
 *  @param delegate          协议对象
 *  @param cancelButtonTitle 取消按钮名称
 *  @param otherButtonTitles 其他按钮
 *
 *  @return MCAlert
 */
- (instancetype)initWithTitle:(NSString *)title message:(NSString *)message delegate:(id<MCAlertDelegate>)delegate cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ... NS_REQUIRES_NIL_TERMINATION; {
    self = [super init];
    if (self) {
        titleText = title;
        messageText = message;
        _lineSpacing = DEFAULT_LINE_SPACING;
        _paragraphSpacing = DEFAULT_LINE_SPACING;
        _contentAlignment = NSTextAlignmentCenter;
        _font = [UIFont systemFontOfSize:14];
        _alertStyle = MCAlertStyleDefault;
        if (delegate){
            _delegate = delegate;
        }
        argsArray = [[NSMutableArray alloc] init];
        hasCancelBtn = NO;
        if (cancelButtonTitle) {
            hasCancelBtn = YES;
            [argsArray insertObject:cancelButtonTitle atIndex:0];
        }
        va_list params; //定义一个指向个数可变的参数列表指针;
        va_start(params,otherButtonTitles);//va_start 得到第一个可变参数地址,
        id arg;
        if (otherButtonTitles) {
            //将第一个参数添加到array
            id prev = otherButtonTitles;
            [argsArray addObject:prev];
            //va_arg 指向下一个参数地址
            //这里是问题的所在 网上的例子，没有保存第一个参数地址，后边循环，指针将不会在指向第一个参数
            while( (arg = va_arg(params,id)) ){
                if ( arg ){
                    [argsArray addObject:arg];
                }
            }
            //置空
            va_end(params);
        }
    }
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(needsDisplay) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
    return self;
}

/**
 *  点击按钮
 */
- (void)buttonClick:(UIButton *)sender{
    if (_delegate && [_delegate respondsToSelector:@selector(alertView:clickedButtonAtIndex:)]){
        [_delegate alertView:self clickedButtonAtIndex:sender.tag];
    }
    if (_clickBlock) {
        _clickBlock(self, sender.tag);
    }
    [self dismiss];
}

/**
 *  点击取消按钮
 */
- (void)cancalClick:(UIButton *)sender{
    if (_delegate && [_delegate respondsToSelector:@selector(alertViewCancel:)]) {
        [_delegate alertViewCancel:self];
    }
    if (_cancelBlock) {
        if (_cancelBlock) {
            _cancelBlock(self);
        }
    }
    if (_delegate && [_delegate respondsToSelector:@selector(alertView:clickedButtonAtIndex:)]){
        [_delegate alertView:self clickedButtonAtIndex:sender.tag];
    }
    if (_clickBlock) {
        _clickBlock(self, sender.tag);
    }
    [self dismiss];
}

/**
 *  显示alertView
 */
- (void)show {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self needsDisplay];
        /*UIWindow *window = ((UIWindow *)[[UIApplication sharedApplication] windows][0]);*/
        UIWindow *window = ((UIWindow *)[UIApplication sharedApplication].keyWindow);
        [window addSubview:self];
        [window endEditing:YES];
        [self performPresentationAnimation];
    });
}

/**
 *  隐藏MCAlertView
 */
- (void)dismiss {
    [self removeFromSuperview];
}

/**
 *  点击空白处,不做操作
 */
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.window resignFirstResponder];
}

/**
 *  显示动画
 */
- (void)performPresentationAnimation {
    CAKeyframeAnimation *bounceAnimation = [CAKeyframeAnimation animation];
    bounceAnimation.duration = 0.35;
//    bounceAnimation.repeatDuration = 1;
    bounceAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    bounceAnimation.values = [NSArray arrayWithObjects:
                              [NSNumber numberWithFloat:0.5],
                              [NSNumber numberWithFloat:1.2],
                              [NSNumber numberWithFloat:0.8],
                              [NSNumber numberWithFloat:1.0],
                              nil];
    
    [_alertView.layer addAnimation:bounceAnimation forKey:@"transform.scale"];
    [UIView animateWithDuration:0.5 animations:^{
        self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
    }];
}

/**
 *  设置message字体
 *
 *  @param font UIFont
 */
- (void)setFont:(UIFont *)font{
    _font = font;
    _messageLabel.font = font;
}

/**
 *  设置message的对齐方式
 *
 *  @param contentAlignment NSTextAlignment
 */
- (void)setContentAlignment:(NSTextAlignment)contentAlignment{
    _contentAlignment = contentAlignment;
}

/**
 *  设置行距
 *
 *  @param lineSpacing CGFloat
 */
- (void)setLineSpacing:(CGFloat)lineSpacing{
    _lineSpacing = lineSpacing;
}

/**
 *  这是段落间距
 *
 *  @param paragraphSpacing CGFloat
 */
- (void)setParagraphSpacing:(CGFloat)paragraphSpacing{
    _paragraphSpacing = paragraphSpacing;
}

/*!
 *  设置Alert的类型
 *  @param alertStyle MCAlertStyle
 */
- (void)setAlertStyle:(MCAlertStyle)alertStyle {
    _alertStyle = alertStyle;
    void (^addKeybordNotification)(void)= ^(){
        // 键盘通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    };
    switch (_alertStyle) {
        case MCAlertStyleDefault:
            // Default
            break;
        case MCAlertStylePlainTextInput:
            _textField = [[UITextField alloc] init];
            addKeybordNotification();
            break;
        case MCAlertStyleSecureTextInput:
            _textField = [[UITextField alloc] init];
            addKeybordNotification();
            break;
        case MCAlertStyleLoginAndPasswordInput:
            _textField = [[UITextField alloc] init];
            _passwordTextField = [[UITextField alloc] init];
            addKeybordNotification();
            break;
        default:
            break;
    }
}
CGRect getScreenBounds() {
    CGRect screenBounds = [UIScreen mainScreen].bounds;
    if ((NSFoundationVersionNumber <= NSFoundationVersionNumber_iOS_7_1) &&
        UIInterfaceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation)) {
        return CGRectMake(0, 0, screenBounds.size.height, screenBounds.size.width);
    }
    return screenBounds;
}
/**
 *  刷新
 */
- (void)needsDisplay {
    if (NSFoundationVersionNumber <= NSFoundationVersionNumber_iOS_7_1) {
        [UIView animateWithDuration:0.3 animations:^{
            self.transform = [[[UIApplication sharedApplication].keyWindow subviews] objectAtIndex:0].transform;
        }];
    }
    self.frame = [UIScreen mainScreen].bounds;
    
    CGRect screenBounds = getScreenBounds();
//     设置背影半透明
//    self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
    
    if (_alertView) {
        [_alertView removeFromSuperview];
        _alertView = nil;
    }
    // 1.alertView
    _alertView = [[UIView alloc] init];
    _alertView.backgroundColor = [UIColor whiteColor];
    [self addSubview:_alertView];
    float width = 280;
    _alertView.frame = CGRectMake(0, 0, width, 200);
    _alertView.layer.cornerRadius = 15;
    _alertView.layer.masksToBounds = YES;
    
    // 2.title
    _titleLabel = [[UILabel alloc] init];
    [_alertView addSubview:_titleLabel];
    _titleLabel.numberOfLines = 3;
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    _titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    _titleLabel.numberOfLines = 3;
    _titleLabel.text = titleText;
    _titleLabel.font = [UIFont boldSystemFontOfSize:18];

    CGRect rect = [_titleLabel textRectForBounds:CGRectMake(0, 20, _alertView.frame.size.width, 100) limitedToNumberOfLines:3];
    _titleLabel.frame = rect;
    _titleLabel.center = CGPointMake(CGRectGetWidth(_alertView.frame)/2, CGRectGetHeight(_titleLabel.frame)/2+30);
    
    CGFloat height = CGRectGetMaxY(_titleLabel.frame);
    
    if (messageText) {
        // 4.messageLabel
        CGFloat leftMargin = 5;
        CGFloat topMargin = 10;
        _messageLabel = [[UITextView alloc] initWithFrame:CGRectMake(leftMargin+3/*+3去平衡右侧滚动条区域导致文字两边不对称的问题*/, CGRectGetMaxY(_titleLabel.frame)+topMargin, _alertView.frame.size.width-leftMargin*2, 35)];
        _messageLabel.backgroundColor = [UIColor clearColor];
        _messageLabel.editable = NO;
        _messageLabel.scrollEnabled = NO;
        _messageLabel.selectable = NO;
        [_messageLabel flashScrollIndicators];   // 闪动滚动条
        [_alertView addSubview:_messageLabel];
        CGRect frame = _messageLabel.frame;
        NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
        style.lineSpacing = _lineSpacing;
        style.paragraphSpacing = _paragraphSpacing;
        style.alignment = _contentAlignment;
        NSDictionary *dic = @{ NSFontAttributeName : _font,
                               NSParagraphStyleAttributeName : style,
                               NSForegroundColorAttributeName: [UIColor colorWithWhite:0.2 alpha:1],
        };

        CGFloat broadWith = (_messageLabel.contentInset.left
                             + _messageLabel.contentInset.right
                             + _messageLabel.textContainerInset.left
                             + _messageLabel.textContainerInset.right
                             + _messageLabel.textContainer.lineFragmentPadding/*左边距*/
                             + _messageLabel.textContainer.lineFragmentPadding/*右边距*/);
        CGFloat textHeight = screenBounds.size.height>screenBounds.size.width?(screenBounds.size.height-64-49-100-(argsArray.count <= 2?44:argsArray.count*44)-leftMargin*2):(screenBounds.size.height-100-(argsArray.count <= 2?44:argsArray.count*44));
        CGSize size = [messageText boundingRectWithSize:CGSizeMake(_alertView.frame.size.width-20-broadWith, LINE_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:dic context:nil].size;
        CGFloat broadHeight  = (_messageLabel.contentInset.top
                                + _messageLabel.contentInset.bottom
                                + _messageLabel.textContainerInset.top
                                + _messageLabel.textContainerInset.bottom);
        CGSize adjustedSize = CGSizeMake(frame.size.width, size.height+broadHeight);
        frame.size.width = _alertView.frame.size.width-leftMargin*2; // 10 TextView 左右边距之和
        frame.size.height = adjustedSize.height;
        if (frame.size.height >= textHeight){
            frame.size.height = textHeight;
            _messageLabel.scrollEnabled = YES;   // 允许滚动
        }else{
            _messageLabel.scrollEnabled = NO;    // 不允许滚动
        }
        _messageLabel.frame = frame;
        _messageLabel.contentSize = CGSizeMake(_alertView.frame.size.width-leftMargin*2, size.height);
        [_messageLabel setAttributedText:[[NSAttributedString alloc] initWithString:messageText attributes:dic]];
        height = CGRectGetMaxY(_messageLabel.frame);
    }
    
    switch (_alertStyle) {
        case MCAlertStyleDefault:
            // Default
            break;
        case MCAlertStylePlainTextInput:
            _textField.frame = CGRectMake(20, height+5, _alertView.bounds.size.width-40, 40);
            _textField.layer.borderColor = [UIColor colorWithRed:0.5176 green:0.5176 blue:0.5176 alpha:1.0].CGColor;
            _textField.layer.borderWidth = 0.3;
            _textField.layer.cornerRadius = 2;
            _textField.delegate = self;
            _textField.backgroundColor = [UIColor clearColor];
            [_alertView addSubview:_textField];
            height = CGRectGetMaxY(_textField.frame);
            break;
        case MCAlertStyleSecureTextInput:
            _textField.frame = CGRectMake(20, height+5, _alertView.bounds.size.width-40, 40);
            _textField.layer.borderColor = [UIColor colorWithRed:0.5176 green:0.5176 blue:0.5176 alpha:1.0].CGColor;
            _textField.layer.borderWidth = 0.3;
            _textField.layer.cornerRadius = 2;
            [_textField setSecureTextEntry:YES];
            _textField.delegate = self;
            _textField.backgroundColor = [UIColor clearColor];
            [_alertView addSubview:_textField];
            height = CGRectGetMaxY(_textField.frame);
            break;
        case MCAlertStyleLoginAndPasswordInput:
            _textField.frame = CGRectMake(20, height+5, _alertView.bounds.size.width-40, 40);
            _textField.layer.borderColor = [UIColor colorWithRed:0.5176 green:0.5176 blue:0.5176 alpha:1.0].CGColor;
            _textField.layer.borderWidth = 0.3;
            _textField.layer.cornerRadius = 2;
            _textField.delegate = self;
            _textField.backgroundColor = [UIColor clearColor];
            [_alertView addSubview:_textField];
            height = CGRectGetMaxY(_textField.frame);
            
            _passwordTextField.frame = CGRectMake(20, height-0.3, _alertView.bounds.size.width-40, 40);
            _passwordTextField.layer.borderColor = [UIColor colorWithRed:0.5176 green:0.5176 blue:0.5176 alpha:1.0].CGColor;
            _passwordTextField.layer.borderWidth = 0.3;
            _passwordTextField.layer.cornerRadius = 2;
            [_passwordTextField setSecureTextEntry:YES];
            _passwordTextField.delegate = self;
            _passwordTextField.backgroundColor = [UIColor clearColor];
            [_alertView addSubview:_passwordTextField];
            height = CGRectGetMaxY(_passwordTextField.frame);
            break;
        default:
            break;
    }
    
    for (UIView *view in _alertView.subviews) {
        if ([view isKindOfClass:[UIButton class]]) {
            [view removeFromSuperview];
        }
    }
    height = height + 15;
    if (hasCancelBtn == YES){
        [argsArray addObject:argsArray[0]];
        [argsArray removeObjectAtIndex:0];
    }
    for (int j = 0; j < [argsArray count]; j++){
        NSString *s = argsArray[j];
        UIButton *button = [[UIButton alloc] init];
        button.backgroundColor = [UIColor clearColor];
        button.frame = CGRectMake(20, height, CGRectGetWidth(_alertView.frame)-40, 44);
        button.layer.cornerRadius = 22;
        button.clipsToBounds = YES;
        button.tag = argsArray.count-1-j;
        [button setTitle:s forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:16];
        [button setTitleColor:j==0?[UIColor whiteColor]:[UIColor grayColor] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor orangeColor] forState:UIControlStateHighlighted];
        if (j == 0) {
            if (_cgColors == nil) {
                _cgColors = @[(__bridge id)[UIColor colorWithRed:255/255.0 green:54/255.0 blue:44/255.0 alpha:1].CGColor,
                            (__bridge id)[UIColor colorWithRed:224/255.0 green:8/255.0 blue:18/255 alpha:1].CGColor];
            }
            CAGradientLayer *gradientLayer = [CAGradientLayer layer];
            gradientLayer.colors = _cgColors;
            gradientLayer.frame = button.bounds;
            gradientLayer.locations = _locations?_locations:@[@0.1, @1.0];
            gradientLayer.startPoint = CGPointMake(0, 0);
            gradientLayer.endPoint = CGPointMake(1.0, 0);
            // gradientLayer.shadowOffset = CGSizeMake(0, 3);
            // gradientLayer.shadowOpacity = 0.4;
            // gradientLayer.shadowColor = UIColor.blueColor.CGColor;
            [button.layer insertSublayer:gradientLayer atIndex:0];
        }
        [_alertView addSubview:button];
        
        if (hasCancelBtn == YES){
            [button addTarget:self action:@selector(cancalClick:) forControlEvents:UIControlEventTouchUpInside];
        }else{
            [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        }
        height = CGRectGetMaxY(button.frame) + 5;
    }
    CGRect rect2 =  _alertView.frame;
    if (argsArray.count <= 2 && messageText.length < 50) {
        rect2.size.height = height;
    }else {
        rect2.size.height = height + 10;
    }
    _alertView.frame = rect2;
    _alertView.center = CGPointMake(screenBounds.size.width/2, screenBounds.size.height/2);
}

#pragma mark - search
/**
 *  显示键盘
 *
 */
- (void)keyBoardWillShow:(NSNotification *)note {
    
    CGRect screenBounds = getScreenBounds();
    CGRect rect = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    [UIView animateWithDuration:[note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue] animations:^{
        CGRect viewRect = self->_alertView.frame;
        viewRect.origin.y = CGRectGetHeight(screenBounds)-rect.size.height-viewRect.size.height;
        self->_alertView.frame = viewRect;
    }completion:^(BOOL finished) {
    }];
}

/**
 *  隐藏键盘
 */
- (void)keyBoardWillHide:(NSNotification *)note{
    [UIView animateWithDuration:[note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue] animations:^{
        self->_alertView.center = self.center;
    }];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [_textField resignFirstResponder];
    [_passwordTextField resignFirstResponder];
}

/**
 *  设置取消的Block copy
 *
 *  @param cancelBlock 取消的Block
 */
- (void)setCancelBlock:(CancelBlock)cancelBlock{
    _cancelBlock = [cancelBlock copy];
}

/**
 *  设置点击的Block copy
 *
 *  @param clickBlock 点击的Block
 */
- (void)setClickBlock:(ClicksBlock)clickBlock{
    _clickBlock = [clickBlock copy];
}

@end
